import 'package:flutter/material.dart';
import 'package:im_module/common/connect_state.dart';
import 'package:im_module/model/ImUserInfoBean.dart';
import 'package:im_module/model/LocationBean.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_application.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_member_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';

class ImProvider with ChangeNotifier {
  ///0 未登录
  ImConnectState _state = ImConnectState.none;

  ImConnectState getState() => _state;

  setState(ImConnectState state) {
    if (_state == state) {
      return;
    }

    this._state = state;
    notifyListeners();
  }

  ///最近会话列表
  List<V2TimConversation?> _mConversation = List.empty(growable: true);

  List<V2TimConversation?> getConversation() => _mConversation;

  //设置新的会话信息
  void setConversation(int page, List<V2TimConversation?>? newConversation) {
    if (newConversation == null) {
      return;
    }
    newConversation.forEach((element) {
      if (element != null) {
        String cid = element.conversationID;

        if (_mConversation.any((ele) => ele!.conversationID == cid)) {
          for (int i = 0; i < _mConversation.length; i++) {
            if (_mConversation[i]!.conversationID == cid) {
              _mConversation[i] = element;
              break;
            }
          }
        } else {
          _mConversation.add(element);
        }
      }
    });
    _mConversation.sort((left, right) => right!.lastMessage!.timestamp!
        .compareTo(left!.lastMessage!.timestamp!));
    notifyListeners();
  }

  ///好友列表
  List<V2TimFriendInfo> _friendList = List.empty(growable: true);

  List<V2TimFriendInfo> get friendList => _friendList;

  setFriendList(List<V2TimFriendInfo>? _applicationList) {
    if (_applicationList == null) {
      return;
    }
    this._friendList = _applicationList;
    notifyListeners();
  }

  ///好友申请未读数量
  int _unFriendReadCount = 0;

  int get unFriendReadCount => _unFriendReadCount;

  setUnFriendReadCount(count) {
    this._unFriendReadCount = count;
    notifyListeners();
  }

  ///好友申请列表
  List<V2TimFriendApplication?> _applyFriends = List.empty(growable: true);

  List<V2TimFriendApplication?> get applyFriends => _applyFriends;

  setApplyFriends(List<V2TimFriendApplication?>? applyFriends) {
    if (applyFriends == null) {
      return;
    }

    //把不是 别人发给我的加好友请求 给移除掉
    applyFriends.removeWhere((element) => element!.type != 1);

    this._applyFriends = applyFriends;
    notifyListeners();
  }

  ///未读消息总数
  int _messageUnReadCount = 0;

  int get messageUnReadCount => _messageUnReadCount;

  setMessageUnReadCount(int count) {
    this._messageUnReadCount = count;
    notifyListeners();
  }

  ///消息缓存
  Map<String, List<V2TimMessage>> _messageMap = new Map();

  Map<String, List<V2TimMessage>> get messageMap => _messageMap;

  ///是否存在该会话信息
  bool containsMessageKey(String key) {
    return _messageMap.containsKey(key);
  }

  ///获取历史记录
  List<V2TimMessage> getHistoryMessage(String key) {
    print("获取历史记录->$key");
    if (containsMessageKey(key)) {
      return _messageMap[key]!;
    } else {
      return List.empty(growable: true);
    }
  }

  ///移除会话消息
  void removeHistoryMessage(String key) {
    if (containsMessageKey(key)) {
      _messageMap.remove(key);
    }
  }

  ///添加消息
  addMessage(String key, V2TimMessage message) {
    //判断是否存在这个用户的聊天记录、如果存在则直接添加消息
    /* if (containsMessageKey(key)) {
      //存在这个聊天
      _messageMap[key]!.add(message);
    } else {
      List<V2TimMessage> _list = List.empty(growable: true);
      _list.add(message);
      _messageMap[key] = _list;
    }
    //排序
    _messageMap[key]!
        .sort((left, right) => left.timestamp!.compareTo(right.timestamp!));
    notifyListeners();*/

    List<V2TimMessage> list = List.empty(growable: true);
    list.add(message);
    addMessages(key, list);
  }

  Map<String?, V2TimMessage> rebuildMap = new Map<String, V2TimMessage>();

  ///添加消息
  addMessages(String key, List<V2TimMessage>? message) {
    if (message == null || message.isEmpty) {
      return;
    }
    if (containsMessageKey(key)) {
      List<V2TimMessage>? values = _messageMap[key];
      values!.addAll(message);

      //以空间换时间、去掉重复的消息数据
      rebuildMap.clear();
      values.forEach((element) {
        rebuildMap[element.msgID] = element;
      });
      //设置去重后的数据
      _messageMap[key] = rebuildMap.values.toList();
    } else {
      _messageMap[key] = message;
    }
    //排序
    _messageMap[key]!
        .sort((left, right) => left.timestamp!.compareTo(right.timestamp!));
    notifyListeners();
  }

  ///发送消息成功 ,替换消息
  void addOneMessageIfNotExits(String key, V2TimMessage message) {
    print("addOneMessageIfNotExits->$key");
    if (_messageMap.containsKey(key)) {
      bool hasMessage =
          _messageMap[key]!.any((element) => element.msgID == message.msgID);

      print("addOneMessageIfNotExits->1->$hasMessage -->${message.toJson()}");
      if (hasMessage) {
        int idx = _messageMap[key]!
            .indexWhere((element) => element.msgID == message.msgID);
        _messageMap[key]![idx] = message;
      } else {
        _messageMap[key]!.add(message);
      }
    } else {
      List<V2TimMessage> _list = List.empty(growable: true);
      _list.add(message);
      _messageMap[key] = _list;
    }
    //排序
    _messageMap[key]!
        .sort((left, right) => left.timestamp!.compareTo(right.timestamp!));
    notifyListeners();
  }

  ///设置消息已读
  updateC2CMessageByUserId(String userid) {
    String key = "c2c_$userid";
    if (_messageMap.containsKey(key)) {
      List<V2TimMessage> msgList = _messageMap[key]!;
      msgList.forEach((element) {
        element.isPeerRead = true;
      });
      _messageMap[key] = msgList;
      notifyListeners();
    } else {
      print("会话列表不存在这个userid key");
    }
  }

  ///查找好友的回调
  ImUserInfoBean? _userInfoBean;

  ImUserInfoBean? get userInfoBean => _userInfoBean;

  setQueryUserInfoBean(ImUserInfoBean? _userInfoBean) {
    if (this._userInfoBean == null && _userInfoBean == null) {
      return;
    }
    this._userInfoBean = _userInfoBean;
    notifyListeners();
  }

  clearQueryUserInfoBean() {
    _userInfoBean = null;
  }

  ///定位获取到定位
  LocationBean? _mLocationBean;

  LocationBean? get mLocationBean => _mLocationBean;

  setLocationBean(LocationBean locationBean) {
    this._mLocationBean = locationBean;
  }

  ///群成员
  List<V2TimGroupMemberFullInfo?> _mGroupMembers = List.empty(growable: true);

  List<V2TimGroupMemberFullInfo?> get mGroupMembers => _mGroupMembers;

  setGroupMembers(List<V2TimGroupMemberFullInfo?> groupMembers) {
    _mGroupMembers.clear();
    _mGroupMembers.addAll(groupMembers);
    notifyListeners();
  }

  ///清除数据
  void clearValue() {
    _mConversation = List.empty(growable: true);
    _friendList = List.empty(growable: true);
    _unFriendReadCount = 0;
    _messageUnReadCount = 0;
    notifyListeners();
  }
}
